/*
 *  Copyright 2007 Genoworks
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */

package com.genoworks.retriever.bigdir;

import java.io.IOException;

import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.BufferedIndexInput;

class BigFileIndexInput extends BufferedIndexInput {

  private BigDiskVolume disk = null;

  private BigFile file = null;

  private long position = 0L;

  private boolean closed = false;

  BigFileIndexInput( BigFile f, BigDiskVolume d ) {
    file = f;
    disk = d;
  }

  protected void readInternal( byte[] b, int offset, int length )
      throws IOException {

    //
    ensureOpen();
    disk.read( file.getSegments(), position, b, offset, length );

    //
    position += length;
  }

  protected void seekInternal( long pos ) throws IOException {
    ensureOpen();
    position = pos;
  }

  public void close() throws IOException {
    closed = true;
  }

  public long length() {
    ensureOpen();
    return file.getLength();
  }

  private void ensureOpen() {
    if ( closed ) {
      throw new AlreadyClosedException( "this VirtualFileIndexInput already closed." );
    }
  }
}
